const jwt = require("jsonwebtoken");
const { User } = require("../models");
const loginUtil = require("./login/util");
const crudUtil = require("./crudUtil/index");

// login
const userLogin = async (ctx, next) => {
  const { username, password } = ctx.request.body || {};
  try {
    const user = await loginUtil.authenticate(User, username, password);
    if (!user) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        message: "Authentication failed: Invalid username or password",
      };
      return;
    }
    // token
    const token = loginUtil.generateToken({
      username: user.username,
      _id: user._id,
    });

    ctx.body = {
      code: 200,
      message: "Login successful",
      data: { token },
    };
  } catch (err) {
    ctx.status = 500;
    ctx.body = {
      code: 500,
      message: "Error during authentication",
      error: err.message,
    };
  }
};

//注册
const userRegister = async (ctx) => {
  const { username, password, } = ctx.request.body || {};

  try {
    const register = await loginUtil.authenticate(User, username, password);
    if (!register) {
      // 创建用户（生产环境请对密码进行哈希）
      const created = await crudUtil.createUser(User, { username, password });
      ctx.body = {
        code: 200,
        message: "User added successfully",
        data: created,
      };
    } else {
      ctx.body = { code: 300, message: "User already exists", data: register };
      return;
    }
  } catch (err) {
    ctx.status = 500;
    ctx.body = { code: 500, message: "Error adding user", error: err.message };
  }
};

module.exports = {
  userLogin,
  userRegister
};
